import { BaseConnection } from "tsrpc";
import { getGateConfig } from "./gateConfigMgr";
import { IGameServerInfo, GameServerCluster } from "./shared/gateClient/GameServer";
import { ServiceType } from "./shared/gameCluster/protocols/serviceProto";

const gameServerList: IGameServerInfo[] = [];

declare module 'tsrpc' {
    export interface BaseConnection {
        serverInfo: IGameServerInfo;
    }
}

export function getAllGameServers() {
    return gameServerList.distinct();
}
export function joinCluster(conn: BaseConnection<ServiceType>,
    gameServerInfo: IGameServerInfo, gameServerCusterKey: string): string | null {
    if (gameServerInfo == null || gameServerCusterKey == null) return "参数不能为空!";
    var cfg = getGateConfig().gameServerCfgList.find(c => c.serverId == gameServerInfo.serverId);
    if (cfg == null) return "找不到该服务器ID!";
    if (cfg.clusterKey != gameServerCusterKey) return "服务器集群密钥错误!";
    updateClusterInfo(conn, gameServerInfo);
    return null;
}
export function updateClusterInfo(conn: BaseConnection<ServiceType>,
    gameServerInfo: IGameServerInfo) {
    if (gameServerInfo == null) return "参数不能为空!";
    gameServerList.remove(s => s.serverId == gameServerInfo.serverId);
    gameServerList.push(gameServerInfo);
    conn.serverInfo = gameServerInfo;
}
export function disconnectCluster(conn: BaseConnection<ServiceType>){
    if(!conn.serverInfo){
        //如果集群节点还没有服务器信息,则直接忽略
        return;
    }
    gameServerList.remove(s => s.serverId == conn.serverInfo.serverId);
}

export default {
    getAllGameServers,
    joinCluster,
    disconnectCluster,
}